﻿/*
* CRM_product_category.cs
*
* 功 能： N/A
* 类 名： CRM_product_category
*
* Ver    变更日期             负责人     变更内容
* ───────────────────────────────────
* V1.0  2015-06-23 18:38:21    黄润伟    
*
* Copyright (c) 2015 www.xhdcrm.com   All rights reserved.
*┌──────────────────────────────────┐
*│　版权所有：黄润伟                      　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System;
using System.Data;
using System.Text;
using System.Web;
using XHD.Common;
using XHD.Controller;

namespace XHD.Server
{
    public class CRM_product_category
    {
        public static BLL.CRM_product_category category = new BLL.CRM_product_category();
        public static Model.CRM_product_category model = new Model.CRM_product_category();

        public HttpContext Context;
        public int emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;


        public CRM_product_category()
        {
        }

        public CRM_product_category(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.ID;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
        }

        public string save()
        {
            string parentid = PageValidate.InputText(request["T_category_parent_val"], 50);
            model.parentid = int.Parse(parentid);
            model.product_category = PageValidate.InputText(request["T_category_name"], 250);
            model.product_icon = PageValidate.InputText(request["T_category_icon"], 250);

            string id = PageValidate.InputText(request["id"], 50);
            string pid = PageValidate.InputText(request["T_category_parent_val"], 50);
            if (PageValidate.IsNumber(id))
            {
                model.id = int.Parse(id);

                DataSet ds = category.GetList(" id=" + int.Parse(id));
                DataRow dr = ds.Tables[0].Rows[0];

                if (int.Parse(id) == int.Parse(pid))
                {
                    return ("false:type");
                }
                else
                {
                    category.Update(model);


                    //日志
                    var log = new sys_log();

                    int UserID = emp_id;
                    string UserName = emp_name;
                    string IPStreet = request.UserHostAddress;
                    string EventTitle = model.product_category;
                    string EventType = "产品类别修改";
                    int EventID = model.id;
                    string Log_Content = null;

                    if (dr["product_category"].ToString() != request["T_category_name"])
                        Log_Content += string.Format("【{0}】{1} → {2} \n", "产品类别", dr["product_category"].ToString(),
                            request["T_category_name"]);

                    if (dr["product_icon"].ToString() != request["T_category_icon"])
                        Log_Content += string.Format("【{0}】{1} → {2} \n", "类别图标", dr["product_icon"].ToString(),
                            request["T_category_icon"]);

                    if (dr["parentid"].ToString() != request["T_category_parent_val"])
                        Log_Content += string.Format("【{0}】{1} → {2} \n", "上级类别", dr["parentid"].ToString(),
                            request["T_category_parent_val"]);

                    if (!string.IsNullOrEmpty(Log_Content))
                        log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);
                }
            }

            else
            {
                model.isDelete = 0;
                category.Add(model);
            }
            return "true";
        }

        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " id";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = " desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = "1=1";
            if (!string.IsNullOrEmpty(request["company"]))
                serchtxt += " and product_category like N'%" + PageValidate.InputText(request["company"], 50) + "%'";

            if (!string.IsNullOrEmpty(request["startdate_del"]))
            {
                serchtxt += " and Delete_time >= '" + PageValidate.InputText(request["startdate_del"], 50) + "'";
            }
            if (!string.IsNullOrEmpty(request["enddate_del"]))
            {
                DateTime enddate = DateTime.Parse(request["enddate_del"]);
                serchtxt += " and Delete_time  <= '" + enddate.AddHours(23).AddMinutes(59).AddSeconds(59) + "'";
            }
            //权限


            string dt = "";
            if (request["grid"] == "tree")
            {
                DataSet ds = category.GetList(0, serchtxt, sorttext);
                dt = "{Rows:[" + GetTasks.GetTasksString(0, ds.Tables[0]) + "]}";
            }
            else
            {
                DataSet ds = category.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);
                dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            }
            return (dt);
        }

        public string tree()
        {
            DataSet ds = category.GetAllList();
            var str = new StringBuilder();
            str.Append("[");
            str.Append(GetTreeString(0, ds.Tables[0]));
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }

        public string combo()
        {
            DataSet ds = category.GetAllList();
            var str = new StringBuilder();
            str.Append("[");
            str.Append("{id:0,text:'无',d_icon:''},");
            str.Append(GetTreeString(0, ds.Tables[0]));
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }

        public string form(string id)
        {
            string dt;
            if (PageValidate.IsNumber(id))
            {
                DataSet ds = category.GetList("id=" + id);
                dt = DataToJson.DataToJSON(ds);
            }
            else
            {
                dt = "{}";
            }

            return (dt);
        }

        //del
        public string del(int id)
        {
            DataSet ds = category.GetList(" id=" + id);

            var product = new BLL.CRM_product();
            if (product.GetList(" category_id=" + id).Tables[0].Rows.Count > 0)
            {
                return ("false:product");
            }
            else if (category.GetList("parentid=" + id).Tables[0].Rows.Count > 0)
            {
                return ("false:parent");
            }
            else
            {
                bool isdel = category.Delete(id);
                if (isdel)
                {
                    //日志
                    string EventType = "产品类别删除";

                    int UserID = emp_id;
                    string UserName = emp_name;
                    string IPStreet = request.UserHostAddress;
                    int EventID = id;
                    string EventTitle = ds.Tables[0].Rows[0]["product_category"].ToString();

                    var log = new sys_log();

                    log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);

                    return ("true");
                }
                else
                {
                    return ("false");
                }
            }
        }

        private static string GetTreeString(int Id, DataTable table)
        {
            DataRow[] rows = table.Select(string.Format("parentid={0}", Id));

            if (rows.Length == 0) return string.Empty;
            ;
            var str = new StringBuilder();

            foreach (DataRow row in rows)
            {
                str.Append("{id:" + (int) row["id"] + ",text:'" + (string) row["product_category"] + "',d_icon:'../../" +
                           (string) row["product_icon"] + "'");

                if (GetTreeString((int) row["id"], table).Length > 0)
                {
                    str.Append(",children:[");
                    str.Append(GetTreeString((int) row["id"], table));
                    str.Append("]},");
                }
                else
                {
                    str.Append("},");
                }
            }
            return str[str.Length - 1] == ',' ? str.ToString(0, str.Length - 1) : str.ToString();
        }
    }
}